<?php

namespace app\admin\controller\statistics;

use app\admin\model\develop\Acuisitionscheme;
use app\admin\model\entrepot\Deliver;
use app\common\controller\Backend;
use think\Db;
use think\db\Connection;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 物料方案
 *
 * @icon fa fa-circle-o
 */
class Materialplan extends Backend
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['getMaterialColourName','getMaterialName','get_material_plan'];

    /**
     * Materialplan模型对象
     * @var \app\admin\model\statistics\Materialplan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\statistics\Materialplan;
        $this->view->assign("attributeList", $this->model->getAttributeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        $type = $this->request->request('type');

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['colour','createuser'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            if ($type == 'dashboard') {
                $where2['attribute'] = 1;
                $list = $this->model
                    ->with(['colour','createuser'])
                    ->where($where)
                    ->where($where2)
                    ->order($sort, $order)
                    ->paginate($limit);

            }

            foreach ($list as $row) {
                $row->visible(['id', 'trademark_printing', 'abbreviation', 'finished_weight', 'feeding_weight', 'attrition_rate', 'attribute', 'name', 'materiallist', 'status']);
                $row->visible(['colour']);
                $row->getRelation('colour')->visible(['name']);
                $row->visible(['createuser']);
                $row->getRelation('createuser')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加 by lhq
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if($params['feeding_weight'] - $params['finished_weight'] < 0) $this->error('投料重量不能大小于成品重量');
                $params['attrition_rate'] = round(($params['feeding_weight'] - $params['finished_weight']) / $params['finished_weight'], 2);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                //查询是否已经存在当前商品主方案
                if ($params['attribute'] == 1) {
                    $w['trademark_printing'] = $params['trademark_printing'];
                    $w['colour_id'] = $params['colour_id'];
                    $w['attribute'] = 1;
                    if ($this->model->where($w)->find()) $this->error('已经存在相同主方案');
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    //添加审核流程修改，添加后状态默认为待审核状态
                    $params['status'] = 2;

                    //                    计算损耗率 sprintf("%.2f",$num);
                    $params['attrition_rate'] = round(($params['feeding_weight'] - $params['finished_weight']) / $params['finished_weight'] * 100, 2);
                    //创建人
                    $params['create_uid'] = $this->auth->id;

                    $result = $this->model->allowField(true)->save($params);

                    if ($result) {
                        $auditData = $params;
                        $auditData['status'] = 0; //待处理
                        $auditData['pid'] = $this->model->getLastInsID();
                        $materialPlanAuditModel = new \app\admin\model\statistics\Materialplanaudit();

                        $res = $materialPlanAuditModel->allowField(true)->save($auditData);
                        if (!$res) {
                            Db::rollback();
                            $this->error('添加失败，稍候再试');
                        }

                        Db::commit();
                        $this->success();
                    } else {
                        Db::rollback();
                        $this->error('添加失败，稍候再试');
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $materialPlanAuditModel = new \app\admin\model\statistics\Materialplanaudit();
        $oldMaterialDetial= $this->model->get($ids);
        if (!$oldMaterialDetial) {
            $this->error(__('No Results were found'));
        }

        if($oldMaterialDetial['status'] == 2 || $oldMaterialDetial['status'] == 3){
            $row = $materialPlanAuditModel->where('pid','eq',$ids)->order('id','desc')->limit(1)->find();
        }else{
            $row = $oldMaterialDetial;
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = true;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    //添加审核流程修改，添加后状态默认为待审核状态
                    $params['status'] = 2;

//                    计算损耗率 sprintf("%.2f",$num);
                    $params['attrition_rate'] = round(($params['feeding_weight'] - $params['finished_weight']) / $params['finished_weight'] * 100, 2);
                    //创建人
                    $params['create_uid'] = $this->auth->id;

                    if ($params['attribute'] == 1) {
                        //查询是否已经存在当前商品主方案
                        $w['trademark_printing'] = $params['trademark_printing'];
                        $w['colour_id'] = $params['colour_id'];
                        $w['attribute'] = $params['attribute'];

                        $w['id'] = array('neq', $ids);
                        if ($this->model->where($w)->count()) {
                            $this->error('已经存在相同主方案');
                        }
                    } else {
                        $w['trademark_printing'] = $params['trademark_printing'];
                        $w['colour_id'] = $params['colour_id'];
                        $w['attribute'] = 1;
                        $w['id'] = array('neq', $ids);

                        if (!$this->model->where($w)->count()) {
                            $params['attribute'] = 1;
                        }
                    }
                    $result = $this->model->where('id','eq',$ids)->setField('status',2);
//                    $result = $row->allowField(true)->save($params);
                    if ($result) {

                        $flag = true;
                        //判断是否存在待审核数据
                        $where['pid'] = $ids;
                        $where['status'] = ['neq', 1];
                        $oldData = $materialPlanAuditModel->where($where)->find();

                        $auditData = $params;
                        $auditData['status'] = 0; //待处理
                        $auditData['pid'] = $ids;
                        if (!$oldData) {
                            $res = $materialPlanAuditModel->allowField(true)->save($auditData);
                        } else {
                            $res = $materialPlanAuditModel->where($where)->update($auditData);
                        }

                        if (!$res) $flag = false;

                        if ($flag != true) {
                            Db::rollback();
                            $this->error('编辑失败，稍候再试');
                        } else {
                            Db::commit();
                            $this->success();
                        }

                    } else {
                        Db::rollback();
                        $this->error('编辑失败，稍候再试');
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $type = $this->request->get("type");
        if ($type == 'materialplandetail') {
            $oldMaterialDetial['colour_name'] = Db::name('colour')->where('id="' . $oldMaterialDetial['colour_id'] . '"')->value('name');
            $this->view->assign("row", $oldMaterialDetial);
            return $this->view->fetch('statistics/materialplan/materialplandetail');
        } else {
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }
    }


    public function getMaterialColourName()
    {
        $res = getSelectPage('material_colour', 'name');
        return $res;
    }

    public function getMaterialName()
    {
        $res = getSelectPage('material', 'name');
        return $res;
    }

    public function get_material_plan()
    {
        $res = getSelectPage('material_plan', 'attribute');
        return $res;
    }
}
